import os
import sys
import shutil
import redis
import logging

sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))

from base.context import Context
from utils.db_object_pool import DBObjectPool
from utils.common_utils import file_md5, remove_envs_by_keys
from database.rdb_client import FileCacheDBHandler
from configure.config_logging import capture_log_init

class FileCacheHandler(object):
    def __init__(self):
        self.__context = Context()
        self.__cache_db_inst = None
        self.__cache_path = ""
        self.env = {} 
        
    def init_env(self):
        self.env = dict(os.environ)
        remove_envs_by_keys(env=self.env, remove_list=["LD_PRELOAD"])
        self.__context.update_work_path(os.path.dirname(self.env["IRGEN_WORK_PATH"]))
        self.init_logger()
        self.__context.check_redis_cached_config()
        self.__cache_path = self.__context.CACHE_DIR
        self.__cache_db_inst = DBObjectPool.get_db_inst_by_name("filecache")
        
    def init_logger(self):
        capture_log_init(log_dir=self.context.LOG_DIR, log_mode="a", log_name=self.context.CAP_LOG_NAME, log_level="DEBUG")
        
    def run_handler(self):
        filepath = sys.argv[-1]
        src_md5 = file_md5(file_path=filepath)
        if not src_md5:
            return
        if not self.__cache_db_inst.is_exists(src_md5):
            self.__cache_db_inst.set_cache_map(file_md5=src_md5, file_path =filepath)
            cache_path = os.path.join(self.__cache_path, src_md5+".src")
            try:
                shutil.copy(filepath, cache_path)
            except OSError as e:
                print(e)   
        return

if __name__ == "__main__":
    handler = FileCacheHandler()
    handler.init_env()
    handler.run_handler()